from django.shortcuts import render

# Create your views here.

import json
from django.http import JsonResponse
from django.views import View
from utils.auth import c2s, already_authorized
from utils.response import wrap_json_response, ReturnCode, CommonResponseMixin
from authorization.models import User


# 测试设置cookie
def test_session(request):
    request.session['message'] = 'Test Django Session OK!'
    response = wrap_json_response(code=ReturnCode.SUCCESS)
    return JsonResponse(data=response, safe=False)


# 测试返回cookie
def test_session2(request):
    print('session content: ', request.session.items()) # 查看请求头中的cookie
    response = wrap_json_response(code=ReturnCode.SUCCESS)
    return JsonResponse(data=response, safe=False)


# 使用 wx.login 得到的临时 code 到微信提供的 code2session 接口授权
def __authorize_by_code(request):
    # 获取请求的参数
    post_data = request.body.decode('utf-8') # 获取 Post 请求的数据
    post_data = json.loads(post_data) # 从json中获取数据
    code = post_data.get('code').strip() # 使用 strip 去除空格
    app_id = post_data.get('appId').strip()
    nickname = post_data.get('nickname').strip()

    # 返回结果
    response = {}
    if not code or not app_id:
        response['message'] = 'authorized failed, need entire authorization data.'
        response['code'] = ReturnCode.BROKEN_AUTHORIZED_DATA
        return JsonResponse(data=response, safe=False)

    data = c2s(app_id, code)
    openid = data.get('openid')
    print('get openid: ', openid)

    # 判断是否正确获取了openid
    if not openid:
        response = wrap_json_response(code=ReturnCode.FAILED, message='auth failed.')
        return JsonResponse(data=response, safe=False)

    # 通过 Django 的 session 中间件设置 cookie
    request.session['open_id'] = openid
    request.session['is_authorized'] = True

    # 判断是否是新用户
    if not User.objects.filter(open_id=openid):
        new_user = User(open_id=openid, nickname=nickname) # 建立新的用户数据
        print('new user: open_id: %s, nickname: %s' % (openid, nickname))
        new_user.save() # 将新建立的用户数据，保存到数据库

    # 返回授权成功的信息
    response = wrap_json_response(code=ReturnCode.SUCCESS, message='auth success.')
    return JsonResponse(data=response, safe=False)


# 用户授权登录
def authorize(request):
    return __authorize_by_code(request)


# 用户注销登录
# 通过清理 session 来
def logout(request):
    request.session.clear() # 通过清除 session 来登出
    response = wrap_json_response(code=ReturnCode.SUCCESS)
    return JsonResponse(data=response, safe=False)


# 判断是否登录
def get_status(request):
    print('call get_status function...')
    if already_authorized(request):
        data = {'is_authorized': 1}
    else:
        data = {'is_authorized': 0}
    response = CommonResponseMixin.wrap_json_response(data=data, code=ReturnCode.SUCCESS)
    return JsonResponse(data=response, safe=False)


# 用户数据相关请求
class UserView(View, CommonResponseMixin):
    # 关注的城市、股票和星座
    def get(self, request):
        if not already_authorized(request):
            response = self.wrap_json_response(code=ReturnCode.SUCCESS)
            return JsonResponse(data=response, safe=False)
        open_id = request.session.get('open_id')
        user = User.objects.get(open_id=open_id)
        data = {}
        data['focus'] = {}
        data['focus']['city'] = json.loads(user.focus_cities)
        data['focus']['stock'] = json.loads(user.focus_stocks)
        data['focus']['constellation'] = json.loads(user.focus_constellations)
        response = self.wrap_json_response(data=data, code=ReturnCode.SUCCESS)
        return JsonResponse(data=response, safe=False)

    def post(self, request):
        if not already_authorized(request):
            response = self.wrap_json_response(code=ReturnCode.SUCCESS)
            return JsonResponse(data=response, safe=False)
        open_id = request.session.get('open_id')
        user = User.objects.get(open_id=open_id)

        received_body = request.body.decode('utf-8')
        received_body = eval(received_body) # 函数用来执行一个字符串表达式，并返回表达式的值

        cities = received_body.get('city')
        stocks = received_body.get('stock')
        constellations = received_body.get('constellation')

        user.focus_cities = json.dumps(cities) # 将数据重新转为json
        user.focus_stocks = json.dumps(stocks)
        user.focus_constellations = json.dumps(constellations)

        user.save() # 保存数据到数据库

        response = self.wrap_json_response(message='modify user info success.', code=ReturnCode.SUCCESS)
        return JsonResponse(data=response, safe=False)
